<template>
    <hb-plus-dialog title="附件预览" :show-footer="false" :visible.sync="visible" width="60%">
        <div class="header">
            <span>
                <doc-icon :data="current"></doc-icon>
                {{ current.name }}
            </span>
            <!-- 头部操作按钮 -->
            <span>
                <!-- v-if="canDownload" -->
                <span class="download">
                    <el-button size="mini" type="primary" icon="iconfont icon-icon-download" @click="$refs.download.click()">下载</el-button>
                    <a :href="current.url" style="display: none" ref="download"></a>
                </span>
                <!-- v-if="canPrint" -->
                <el-button size="mini" @click="onPrint">打印</el-button>
            </span>
        </div>

        <div class="main" v-loading="loading">
            <div class="content">
                <!-- 预览内容 -->
                <iframe v-if="iframeSrc" :key="iframeSrc" :src="iframeSrc" frameborder="0" ref="iframe" target="_blank"></iframe>

                <empty-data v-else-if="!current">
                    <span>加载中...</span>
                </empty-data>
                <empty-data v-else-if="unsupported">
                    <template v-slot:icon><svg-icon icon="unsupported"></svg-icon></template>
                    <span>不支持该类型文件预览</span>
                </empty-data>
                <empty-data v-else-if="unauthorized">
                    <template v-slot:icon><svg-icon icon="unauthorized"></svg-icon></template>
                    <span>你没有该文件的预览权限</span>
                </empty-data>
            </div>

            <!-- 切换文件列表 -->
            <div class="footer">
                <file-gallery
                    :current.sync="current"
                    :parent-id="parentId"
                    :id="id"
                    :versionId="versionId"
                    :linkId="linkId"
                    :accessCode="accessCode"
                    v-bind="$attrs"
                    @update-preview="updatePreview"
                ></file-gallery>
            </div>
        </div>
    </hb-plus-dialog>
</template>

<script>
import { getPreviewConfigApi } from '../api/oss';
import FileGallery from './file-gallery';
import EmptyData from '../empty-data';
import DocIcon from './doc-icon';
import { cloneDeep } from 'lodash';

export default {
    props: {
        value: {
            type: Boolean,
            default: false
        },
        previewData: {
            //name, url
            type: Object,
            default: () => {}
        }
    },
    components: {
        FileGallery,
        EmptyData,
        DocIcon
    },
    data() {
        return {
            iframeSrc: '',
            loading: false,
            current: {},
            parentId: '',
            id: '',
            versionId: '', // 历史版本预览
            linkId: '', // 外链预览
            accessCode: '', // 外链提取码
            unsupported: false,
            unauthorized: false
        };
    },
    computed: {
        visible: {
            get() {
                return this.value;
            },
            set(val) {
                !val && this.$emit('input', val);
            }
        }
    },
    watch: {
        value(val) {
            if (val) {
                this.current = cloneDeep(this.previewData);
                this.handlePreview(this.current.name, this.current.url);
            }
        }
    },
    methods: {
        /* 打印 */
        onPrint() {
            if (!this.$refs.iframe) return;
            if (this.$refs.iframe.contentWindow) {
                this.$refs.iframe.contentWindow.postMessage({ type: 'print' }, '*');
            }
        },

        /* 更新当前预览对象 */
        updateCurrent(row) {
            this.current = row;
        },

        /* 更新预览 */
        updatePreview(data) {
            const { name, url } = data;
            this.handlePreview(name, url);
            this.updateCurrent(data);
        },

        /* 处理预览 */
        async handlePreview(name, url) {
            try {
                // await previewApi(this.current);
                this.loading = true;
                let res = await getPreviewConfigApi().catch(() => {
                    this.loading = false;
                });
                this.loading = false;
                if (res.code === 0) {
                    let userInfo = JSON.parse(sessionStorage.getItem('vuex')).user?.userInfo;
                    let onlyOfficeWeb = res?.data?.deploy?.onlyOfficeWeb;
                    let previewWeb = res?.data?.deploy?.previewWeb;
                    const query = {
                        userid: userInfo?.staffId,
                        username: userInfo?.name,
                        onlyOfficeUrl: this.expr(onlyOfficeWeb),
                        src: url,
                        filename: name,
                        archive: false //这里是设置归档的文件,以便预览的时候用文档下载链接去预览
                    };
                    const q = Object.entries(query)
                        .map(([k, v]) => {
                            return encodeURIComponent(k) + '=' + encodeURIComponent(v);
                            // return k + '=' + v;
                        })
                        .join('&');

                    this.iframeSrc = `${this.expr(previewWeb)}/#/preview?${q}`;
                }
            } catch (error) {}
        },

        /* 处理预览地址 */
        expr(url) {
            const protocol = location.protocol;
            const hostname = location.hostname;
            const port = location.port;
            const pathname = location.pathname;
            const body = 'return `' + url?.replace(/({\w+})/g, (_, c) => `$${_}`) + '`';
            // eslint-disable-next-line
            return new Function('protocol', 'hostname', 'port', 'pathname', body)(protocol, hostname, port, pathname);
        }
    }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
    margin-top: 3vh !important;
    margin-bottom: 18px;
}
iframe {
    width: 100%;
    height: 600px;
}
.header {
    display: flex;
    height: 36px;
    justify-content: space-between;
    align-items: center;
    color: #242833;
    box-sizing: border-box;
    padding-bottom: 8px;
}

.main {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
}

.content {
    flex: 1 1 auto;
}

.footer {
    flex: 0 0 auto;
}

::v-deep .el-button--mini {
    padding: 5px 12px;
}
.download {
    margin-right: 12px;
    a {
        display: none;
    }
}
</style>
